﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Windows.Forms;

namespace NewLand
{
    public static class Extension
    {
        public static int ToInt(this string val)
        {
            return int.Parse(val.ToString());
        }
    }

    public class NewLandBarcode
    {
        public Form BaseForm;
        public NewLandBarcode(Form BaseForm)
        {
            this.BaseForm = BaseForm;
            BaseForm.FormClosing += BaseForm_FormClosing;
        }

        void BaseForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            TumunuKapat();
        }
        public class Cihaz
        {
            public int CihazNo;
            public string Buffer;
            public SerialPort Port;
            Form BaseForm;
            public Cihaz(int CihazNo, int PortNo)
            {
                this.CihazNo = CihazNo;

                Port = new System.IO.Ports.SerialPort("COM" + PortNo);
                Port.BaudRate = 57600;
                Port.DataBits = 8;
                Port.Parity = System.IO.Ports.Parity.None;
                Port.StopBits = StopBits.One;
                Port.Handshake = Handshake.None;
                Port.DtrEnable = true;
                Port.Close();
                Port.Open();
            }
        }

        public List<Cihaz> Cihazlar = new List<Cihaz>();

        public void CihazEkle(int CihazNo, int PortNo)
        {
            try
            {
                Cihaz cihaz = new Cihaz(CihazNo, PortNo);
                cihaz.Port.DataReceived += port_DataReceived;
                Cihazlar.Add(cihaz);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        public void TumunuKapat()
        {
            foreach (Cihaz cihaz in Cihazlar)
                cihaz.Port.Close();

            Cihazlar.Clear();
        }


        void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort senderPort = sender as SerialPort;
            Cihaz senderCihaz = null;
            foreach (Cihaz cihaz in Cihazlar)
                if (cihaz.Port.PortName == senderPort.PortName)
                    senderCihaz = cihaz;

            string s1 = "";

            int bytesToRead = senderPort.BytesToRead;
            byte[] buffer = new byte[bytesToRead];
            senderPort.Read(buffer, 0, bytesToRead);

            s1 = senderPort.Encoding.GetString(buffer);
            if (!s1.Contains("\r\n"))
            {
                senderCihaz.Buffer += s1;
                return;
            }
            else
            {
                string[] pairs = s1.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                foreach (string val in pairs)
                {

                    string s2 = val; // val.Replace("\r\n", "");

                    s2 = senderCihaz.Buffer + s2;
                    senderCihaz.Buffer = "";

                    string s3 = s2.TrimStart(new char[] { '0' });
                    string s4 = s3.Substring(0, s3.Length - 1);

                    string[] vals = s4.Split(",".ToCharArray());
                    string[] dates = vals[0].Split("/".ToCharArray());
                    string[] times = vals[1].Split(":".ToCharArray());
                    DateTime date = new DateTime(
                                                     dates[0].ToInt()
                                                    , dates[1].ToInt()
                                                    , dates[2].ToInt()
                                                    , times[0].ToInt()
                                                    , times[1].ToInt()
                                                    , times[2].ToInt()

                                                    );

                    date = date.AddHours(-5); //tarih saati set edemediğim için

                    if (BarcodeRead != null)
                        BaseForm.BeginInvoke(new BarcodeReadHandler(BarcodeRead), new object[] { vals[2].ToInt(), date, senderCihaz.CihazNo });
                }
            }
        }

        public delegate void BarcodeReadHandler(int Barcode, DateTime Tarih, int CihazNo);
        public event BarcodeReadHandler BarcodeRead;
    }
}